package org.btik.light.nbi;


import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.btik.context.thread.SystemControlAble;
import org.btik.light.meta.base.Command;
import org.btik.light.server.platform.common.api.service.OperationServer;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class LightNBIServer extends Thread implements SystemControlAble {
    private final Log log = LogFactory.getLog(LightNBIServer.class);
    private int nbiPort;

    private volatile boolean runFlag = true;

    private OperationServer operationServer;

    public void setOperationServer(OperationServer operationServer) {
        this.operationServer = operationServer;
    }

    public void setNbiPort(int nbiPort) {
        this.nbiPort = nbiPort;
    }

    @Override
    public void run() {
        log.info("nbi server started");
        try (DatagramSocket serverSocket = new DatagramSocket(nbiPort)) {
            byte[] buffer = new byte[255];
            DatagramPacket datagramPacket = new DatagramPacket(buffer, 0, buffer.length);
            while (runFlag) {
                serverSocket.receive(datagramPacket);
                byte[] data = datagramPacket.getData();
                int length = datagramPacket.getLength();
                Command command = NbiCmdParser.parse(data, length);
                if (command == null) {
                    continue;
                }
                operationServer.sendAsyncCmdOrMsg(command);
            }
        } catch (IOException e) {
            log.error("nbi server exits:", e);
            this.runFlag = false;
        }
    }

    @Override
    public void shutdown(String msg) {
        runFlag = false;
    }

    public LightNBIServer() {
        super("nbi-server");
    }
}
